package cn.fl.warrant.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.warrant.service.IArcBorrowMainService;
import cn.fl.warrant.transform.ArcBorrowMainVOTransform;
import cn.fl.warrant.vo.ArcBorrowMainVO;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.condition.FlowQueryCondition;
import fl.flow.facade.flow.dto.FlowMyTaskDTO;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.warrant.facade.archive.api.IArcBorrowMainApiService;
import fl.warrant.facade.archive.condition.ArcBorrowDetailQueryCondition;
import fl.warrant.facade.archive.condition.ArcBorrowMainQueryCondition;

/**
 * @Description: 借阅业务 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class ArcBorrowMainServiceImpl implements IArcBorrowMainService {
	
	private static final Logger logger = LoggerFactory.getLogger(IArcBorrowMainService.class);
	
	@Autowired
	private ISysDictionaryApiService sysDictionaryApi;
	@Autowired
	private IArcBorrowMainApiService arcBorrowMainApiService;
	@Autowired
	private IFlowApiService flowApiService;//流程API接口服务
	
	/**
	 * 根据字段代码组获取代码值集合
	 * @param grpCd 代码组值
	 * @param sysCd 系统代码
	 * @param orgCd 组织结构代码
	 * @return 值
	 * @throws BaseException
	 */
	@Override
	public List<KeyValueVO> getKvList(String grpCd) throws BaseException {
		List<KeyValueVO>  keyValueList = null;
		List<SysDictionaryDTO> dictionaryList = this.sysDictionaryApi
				.searchGroup(CurrentThreadContext.getCurrentSysCd(),
						CurrentThreadContext.getCurrentOrgCd(), grpCd);
		if(CollectionUtils.isNotEmpty(dictionaryList)){
			keyValueList = new ArrayList<>();
			for (SysDictionaryDTO sysDictionaryDTO : dictionaryList) {
				KeyValueVO keyValue = new KeyValueVO();
				keyValue.setKey(sysDictionaryDTO.getCode());
				keyValue.setValue(sysDictionaryDTO.getCodeNm());
				keyValueList.add(keyValue);
			}
		}
		return keyValueList;
	}
	
	/**
	 * 根据字段代码组获取代码值集合
	 * @param grpCd 代码组值
	 * @param sysCd 系统代码
	 * @param orgCd 组织结构代码
	 * @return 值
	 * @throws BaseException
	 */
	@Override
	public List<KeyValueVO> getKvDescList(String grpCd) throws BaseException {
		List<KeyValueVO>  keyValueList = null;
		List<SysDictionaryDTO> dictionaryList = this.sysDictionaryApi
				.searchGroup(CurrentThreadContext.getCurrentSysCd(),
						CurrentThreadContext.getCurrentOrgCd(), grpCd);
		if(CollectionUtils.isNotEmpty(dictionaryList)){
			keyValueList = new ArrayList<>();
			for (SysDictionaryDTO sysDictionaryDTO : dictionaryList) {
				KeyValueVO keyValue = new KeyValueVO();
				keyValue.setKey(sysDictionaryDTO.getCodeNm());
				keyValue.setValue(sysDictionaryDTO.getCodeDesc());
				keyValueList.add(keyValue);
			}
		}
		return keyValueList;
	}
	
	@Override
	public ArcBorrowMainVO selectById(Long id) throws BaseException{
		return ArcBorrowMainVOTransform.toVO(arcBorrowMainApiService.selectById(id));
	}

	@Override
	public Long add(ArcBorrowMainVO entity) throws BaseException{
		return this.arcBorrowMainApiService.add(ArcBorrowMainVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		return this.arcBorrowMainApiService.removeById(id);
	}
	


	@Override
	public boolean update(ArcBorrowMainVO entity) throws BaseException{
		return this.arcBorrowMainApiService.update(ArcBorrowMainVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		return this.arcBorrowMainApiService.searchListPage(page);
	}

	@Override
	public Long borrowApplyStart(ArcBorrowMainVO entity) throws BaseException {
		return this.arcBorrowMainApiService.borrowApplyStart(ArcBorrowMainVOTransform.toDTO(entity));
	}
	
	@Override
	public DataResultDTO addFlowStart(FlowStartParamsDTO flowStartParamsDTO) throws BaseException{
		if(StringUtils.isEmpty(flowStartParamsDTO.getCrtUsrId()) || StringUtils.isEmpty(flowStartParamsDTO.getBusinessKey())){
			BaseLogUtils.info(logger, "addFlowStart", "用户ID和业务数据主键必须要存在!",CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "用户ID和业务数据主键必须要存在!");
		}
		return this.arcBorrowMainApiService.addFlowStart(flowStartParamsDTO);
	}

	/**
	 * 借阅流程
	 * @return
	 */
	public Pager borrowFlowPage(Pager Page) throws BaseException{
		return this.arcBorrowMainApiService.borrowFlowPage(Page);
	}
	/**
	 * 借阅历史
	 * @return
	 */
	public Pager borrowHistoryPage(Pager Page) throws BaseException{
		return this.arcBorrowMainApiService.borrowHistoryPage(Page);
	}
	/**
	 * 借阅记录
	 * @return
	 */
	public List<Map<String, Object>> borrowRecord(ArcBorrowDetailQueryCondition condition) throws BaseException {
		return arcBorrowMainApiService.borrowRecord(condition);
	}
	
	/**
	 * 借阅申请修改
	 */
	public void borrowApplyUpdate(ArcBorrowMainVO entity) throws BaseException {
		arcBorrowMainApiService.borrowApplyUpdate(ArcBorrowMainVOTransform.toDTO(entity));
	}

	@Override
	public String getCstNm(String contractNo) throws BaseException {
		return arcBorrowMainApiService.getCstNm(contractNo);
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<FlowMyTaskDTO> searchMyTaskMap(String pNO)
			throws BaseException {
	
		try{
			Pager page = new Pager();
			page.setCurrentPage(1);
			page.setEveryPage(100);
			FlowQueryCondition flowQueryCondition = new FlowQueryCondition();
			flowQueryCondition.setSysCd(CurrentThreadContext.getFlServiceSysCd());
			flowQueryCondition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowQueryCondition.setProcNo(pNO);
			page.setCondition(flowQueryCondition);
			page = this.flowApiService.searchTaskRecordManagePage(page, CurrentThreadContext.getCurrentUserId(), "");
			List<FlowMyTaskDTO> flowMyTaskList = (List<FlowMyTaskDTO>)page.getResultList();
			return flowMyTaskList;
		}catch(Exception e){
			e.printStackTrace();
			BaseLogUtils.error(logger, "searchMyTaskMap", "获取流程引擎待办任务失败!" + e.getMessage());
		}
		return null;
	}

	/**
	 * 判断是否能发起延期申请
	 * @param originalReturn 是否计划归还
	 * @param pNo 流程号
	 * @return true:可以发起延期申请
	 * @throws BaseException
	 */
	@Override
	public boolean canDelayApply(String originalReturn, String pNo)
			throws BaseException {
		
		if("1".equals(originalReturn)) {//计划归还 
			if(StringUtils.isNotBlank(pNo)) {//流程号
				List<FlowMyTaskDTO> flowMyTaskDTOList =  this.searchMyTaskMap(pNo);
				if (flowMyTaskDTOList != null && flowMyTaskDTOList.size() >0) {
					FlowMyTaskDTO flowMyTaskDTO = flowMyTaskDTOList.get(0);
					if("FLOW_0000_ARC02_001_007".equals(flowMyTaskDTO.getTaskDefKey())) {//节点：借阅人归还
						return true;
					}
				}
			}
		}
		return false;
	}

	@Override
	public boolean getFlowIsCanBeStart(Long dataId, String sysCd, String wordsInTheTable, String procDefKey, String procDefId,boolean isFlowStatePassCanbeStart) throws BaseException {
		return arcBorrowMainApiService.getFlowIsCanBeStart(dataId,  sysCd,  wordsInTheTable,  procDefKey,  procDefId,isFlowStatePassCanbeStart) ;
	}
	
	
	/**
	 * 根据合同号获取客户经理组织架构
	 * @param contractNo
	 * @return
	 * @throws BaseException
	 */
	public String getCstMgrOrgCd(String contractNo) throws BaseException{
		return arcBorrowMainApiService.getCstMgrOrgCd(contractNo);
	}

	@Override
	public List<ArcBorrowMainVO> selectList(ArcBorrowMainQueryCondition qc) throws BaseException {
		return ArcBorrowMainVOTransform.toVOList(arcBorrowMainApiService.selectList(qc));
	}

	/**
	 * 查询客户逾期情况
	 * @param cstId
	 * @return
	 * @throws BaseException
	 */
	@Override
    public Long selectCstIsOvd(Long cstId) throws BaseException {
        return this.arcBorrowMainApiService.selectCstIsOvd(cstId);
    }
}
